package com.module.ble.ui.colorSelection

import android.graphics.Color
import android.util.Log
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.common.app.core.RouterHub
import com.common.app.data.bean.BaseCityModel
import com.common.app.data.bean.IntelligentTouchOptionModel
import com.common.app.data.bean.KeyBundle
import com.common.app.data.bean.KeyPre
import com.common.app.utls.ColorUtils
import com.common.app.utls.ColorUtils.colorToHexStringWithAlpha
import com.common.app.utls.ColorUtils.hexColorToInt
import com.common.app.utls.HeadTitleUtils
import com.common.base.app.activity.BaseNavActivity
import com.common.base.app.extras.setOnClickListener
import com.common.base.utils.SpUtilsManagement
import com.common.base.utils.StatusBarUtils
import com.common.base.utils.ViewUtils
import com.module.ble.R
import com.module.ble.databinding.BleActivityColorSelectionBinding
import com.module.ble.ui.colorSelection.SelectLightColorDialog.OnSelectLightColorDialogListener
import com.module.ble.utils.LightingEffectConfig
import com.module.ble.utils.LightingEffectDefValue
import com.module.ble.widget.CusColorPickView.OnColorChangedListener
import com.module.ble.widget.customseekbar.IndicatorSeekBar
import kotlin.text.toInt


/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2025/09/29
 * <p>
 * 描述：颜色选择页面
 * <p>
 * 修订历史：
 */
@Route(path = RouterHub.ROUTER_SELECT_COLOR)
class ColorSelectionActivity : BaseNavActivity<BleActivityColorSelectionBinding>(),
    View.OnClickListener {

    override fun getViewContentBinding() = BleActivityColorSelectionBinding.inflate(layoutInflater)

    override fun getPlaceholderView() = mViewBinding.mPlaceholderView

    override fun isShowToolBar(): Boolean = false
    override fun isStatusBarTranslate(): Boolean = true

    @Autowired(name = KeyBundle.BUNDLE_KEY)
    @JvmField
    var busType: Int = 0

    var mIntelligentTouchOptionModel: IntelligentTouchOptionModel? = null

    var modeConfigBean: BaseCityModel? = null
    var durationConfigBean: BaseCityModel? = null
    var timedIntervalConfigBean: BaseCityModel? = null

    private val selectLightColorDialog by lazy { SelectLightColorDialog(this) }

    private val modeConfigDialog by lazy { CommonLightingEffectConfigDialog(this, dataType = 0, mType = busType) }
    private val durationConfigDialog by lazy { CommonLightingEffectConfigDialog(this, dataType = 1, mType = busType) }
    private val timedIntervalConfigDialog by lazy { CommonLightingEffectConfigDialog(this, dataType = 2, mType = busType) }

    override fun initViews() {
        super.initViews()
        StatusBarUtils.setStatusBarHeight(mViewContentBinding.statusView)
        StatusBarUtils.setStatusBarForegroundColor(this, true)

        val headTitleUtils = HeadTitleUtils(this)
        headTitleUtils.setTitle(getString(R.string.ble_color_picker_title))
        headTitleUtils.setLineStyle(10)
    }

    override fun initEvents() {
        super.initEvents()

        mViewContentBinding.inbBrightness.setOnSeekChangeListener(object : IndicatorSeekBar.OnSeekBarChangeListener{
            override fun onProgressChanged(
                seekBar: IndicatorSeekBar?,
                progress: Int,
                progressFloat: Float,
                fromUserTouch: Boolean
            ) {
//                // 使用 HSV 颜色模型调整亮度
//                val hsv = FloatArray(3)
//                Color.colorToHSV(currentColorValue, hsv)
//                // 调整亮度值 (V值)，progress 0-100 对应亮度 0.0-1.0
//                hsv[2] = progress / 100f
//                adjustedColorValue = Color.HSVToColor(Color.alpha(currentColorValue), hsv)
//                mViewContentBinding.tvColorValue.text = "${getString(R.string.ble_color_hue_hint)}  ${colorToHexStringWithAlpha(adjustedColorValue)}"
//                mViewContentBinding.cvColorValue.setCardBackgroundColor(adjustedColorValue)

                mViewContentBinding.tvBrightnessValue.text = "${getString(R.string.ble_color_brightness_hint)}  ${progress}%"
            }

            override fun onSectionChanged(
                seekBar: IndicatorSeekBar?,
                thumbPosOnTick: Int,
                textBelowTick: String?,
                fromUserTouch: Boolean
            ) {
            }

            override fun onStartTrackingTouch(
                seekBar: IndicatorSeekBar?,
                thumbPosOnTick: Int
            ) {
            }

            override fun onStopTrackingTouch(seekBar: IndicatorSeekBar?) {
            }

        })

        mViewContentBinding.inbVelocity.setOnSeekChangeListener(object : IndicatorSeekBar.OnSeekBarChangeListener{
            override fun onProgressChanged(
                seekBar: IndicatorSeekBar?,
                progress: Int,
                progressFloat: Float,
                fromUserTouch: Boolean
            ) {
                mViewContentBinding.tvVelocityValue.text = "${getString(R.string.common_velocity_hint)}  $progress"
            }

            override fun onSectionChanged(
                seekBar: IndicatorSeekBar?,
                thumbPosOnTick: Int,
                textBelowTick: String?,
                fromUserTouch: Boolean
            ) {
            }

            override fun onStartTrackingTouch(
                seekBar: IndicatorSeekBar?,
                thumbPosOnTick: Int
            ) {
            }

            override fun onStopTrackingTouch(seekBar: IndicatorSeekBar?) {
            }

        })

        selectLightColorDialog.setListener(object:OnSelectLightColorDialogListener{
            override fun onSelectLightColorClick(mData: IntelligentTouchOptionModel) {
                mIntelligentTouchOptionModel = mData
                mViewContentBinding.cvColorValue.setCardBackgroundColor(hexColorToInt(mData.name?:""))
            }
        })

        modeConfigDialog.setListener(object : CommonLightingEffectConfigDialog.OnSelectListener{
            override fun onSelectClick(
                mType: Int,
                mBean: BaseCityModel
            ) {
                mViewContentBinding.tvMode.text = mBean.name
                modeConfigBean = mBean
            }
        })

        durationConfigDialog.setListener(object : CommonLightingEffectConfigDialog.OnSelectListener{
            override fun onSelectClick(
                mType: Int,
                mBean: BaseCityModel
            ) {
                mViewContentBinding.tvDuration.text = mBean.name
                durationConfigBean = mBean
            }
        })

        timedIntervalConfigDialog.setListener(object : CommonLightingEffectConfigDialog.OnSelectListener{
            override fun onSelectClick(
                mType: Int,
                mBean: BaseCityModel
            ) {
                mViewContentBinding.tvTimedInterval.text = mBean.name
                timedIntervalConfigBean = mBean
            }
        })

        mViewContentBinding.totalMode.setOnClickListener(onClick = this)
        mViewContentBinding.totalColor.setOnClickListener(onClick = this)
        mViewContentBinding.totalDuration.setOnClickListener(onClick = this)
        mViewContentBinding.totalTimedInterval.setOnClickListener(onClick = this)
        mViewContentBinding.btnConfirm.setOnClickListener(onClick = this)
    }

    override fun lazyInitData() {
        super.lazyInitData()

        val tempName = SpUtilsManagement.getString(when(busType){
            LightingEffectConfig.TYPE_LIGHTING_GESTURE->KeyPre.KEY_LIGHTING_GESTURE_COLOR_VALUE
            LightingEffectConfig.TYPE_LIGHTING_SPORTS->KeyPre.KEY_LIGHTING_SPORTS_COLOR_VALUE
            else -> KeyPre.KEY_LIGHTING_TIMING_COLOR_VALUE
        },ColorUtils.defColor)

        mViewContentBinding.cvColorValue.setCardBackgroundColor(hexColorToInt(tempName))


        SpUtilsManagement.getInt("${KeyPre.KEY_LIGHTING_EFFECT_MODE_VALUE}_$busType", 0).let {
            mViewContentBinding.tvMode.text = when(it){
                1->ViewUtils.getString(R.string.ble_lighting_mode_cl_hint)
                2->ViewUtils.getString(R.string.ble_lighting_mode_breathe_hint)
                3->ViewUtils.getString(R.string.ble_lighting_mode_rainbow_hint)
                else -> ""
            }

        }
        SpUtilsManagement.getInt("${KeyPre.KEY_LIGHTING_EFFECT_DURATION_VALUE}_$busType", 0).let {
            mViewContentBinding.tvDuration.text = if (0 >= it) "" else it.toString()
        }
        SpUtilsManagement.getInt("${KeyPre.KEY_LIGHTING_EFFECT_INTERVAL_VALUE}_$busType", 0).let {
            mViewContentBinding.tvTimedInterval.text = if (0 >= it) "" else it.toString()

        }
    }

    override fun onClick(v: View?) {
        when (v) {
            mViewContentBinding.totalMode -> modeConfigDialog.show()
            mViewContentBinding.totalColor -> selectLightColorDialog.show(busType)
            mViewContentBinding.totalDuration -> durationConfigDialog.show()
            mViewContentBinding.totalTimedInterval -> timedIntervalConfigDialog.show()
            mViewContentBinding.btnConfirm ->{
                mIntelligentTouchOptionModel?.let {
                    SpUtilsManagement.putString(when(busType){
                        LightingEffectConfig.TYPE_LIGHTING_GESTURE->KeyPre.KEY_LIGHTING_GESTURE_COLOR_VALUE
                        LightingEffectConfig.TYPE_LIGHTING_SPORTS->KeyPre.KEY_LIGHTING_SPORTS_COLOR_VALUE
                        else -> KeyPre.KEY_LIGHTING_TIMING_COLOR_VALUE
                    }, it.name?:"")
                }
                modeConfigBean?.let {
                    SpUtilsManagement.putInt("${KeyPre.KEY_LIGHTING_EFFECT_MODE_VALUE}_$busType", it.code.toInt())
                }
                durationConfigBean?.let {
                    SpUtilsManagement.putInt("${KeyPre.KEY_LIGHTING_EFFECT_DURATION_VALUE}_$busType", it.code.toInt())
                }
                timedIntervalConfigBean?.let {
                    SpUtilsManagement.putInt("${KeyPre.KEY_LIGHTING_EFFECT_INTERVAL_VALUE}_$busType", it.code.toInt())
                }
                finish()
            }
        }
    }

    override fun onStart() {
        super.onStart()
    }

    override fun onStop() {
        super.onStop()
    }
    override fun onDestroy() {
        super.onDestroy()
    }
}